<template>
    <div id="content">
        <!-- 内容 -->
        <el-row :gutter="10" class="chart_top">
            <el-col :span="24">
                <el-card shadow="always" :style="{width:'100%',height:autoHeight+'px'}">
                    <div :style="{position: 'relative',width:'100%',height:autoHeight+'px'}">
                        <el-row class="data_box" style="position:absolute;top:2px;right:10px;z-index:1999;">
                            <el-popover
                                placement="bottom"
                                width="650"
                                trigger="hover">
                                <el-button  type="primary" slot="reference">{{search.macName}}</el-button>
                                <h2 style="color: #FFFFFF;background-color: #242f42;margin:15px 0 15px 0;padding:5px 0px 5px 15px; border-radius:3px;">请选择设备</h2>
                                <div style="width:90%;height:40%;border:1px solid gray; margin:0 auto; padding:5px 5px 5px 5px;">
                                        <span v-for="(item,i) in search.machineData">
                                        <el-radio v-model="search.macId" :label="item.id" @change="syschMacName">{{item.name}}</el-radio>
                                        &nbsp;
                                        </span>

                                </div>
                            </el-popover>
                                <!-- <el-date-picker
                                v-model="search.showTime"
                                type="date"
                                placeholder="选择日期"
                                style="width:130px;"
                                @change="showGanttMapByDate"
                                > -->
                                <!-- type="daterange" -->
                                <!-- <el-date-picker
                                v-model="search.showTime"
                                type="datetimerange"
                                @change="showGanttMapByDate"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                                </el-date-picker> -->
                                <span>开始日期:</span>
                                <el-date-picker
                                v-model="grid.startTime"
                                type="date"
                                @change="showGanttMapStartTime"
                                value-format="yyyy-MM-dd"
                                placeholder="开始日期">
                                </el-date-picker>
                                <el-radio v-model="beginRadio" label="08:30:00" @change="radioChangeStart">白班</el-radio>
                                <el-radio v-model="beginRadio" label="20:30:00" @change="radioChangeStart" style="margin-left:-10px;">晚班</el-radio>
                                <span>结束日期:</span>
                                <el-date-picker
                                v-model="grid.endTime"
                                type="date"
                                @change="showGanttMapEndTime"
                                value-format="yyyy-MM-dd"
                                placeholder="结束日期">
                                </el-date-picker>
                                <el-radio v-model="endRadio" label="08:30:00"  @change="radioChangeEnd">白班</el-radio>
                                <el-radio v-model="endRadio" label="20:30:00"  @change="radioChangeEnd" style="margin-left:-10px;">晚班</el-radio>

                        </el-row>
                        <el-row>
                        <div id="zp" style="width:100%;height:800px;"></div>

                        </el-row>
                    </div>
                </el-card>
            </el-col>
            <!-- <el-col :span="12">
                <el-card shadow="always" :style="{width:'100%',height:autoHeight+'px'}">
                    <div style="position: relative;">
                        <div id="ed">1231231</div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="always" :style="{width:'100%',height:autoHeight+'px'}">
                    <div style="position: relative;">
                        <div id="bz">123131</div>
                    </div>
                </el-card>
            </el-col> -->
        </el-row>
        <div id="popover">
            <el-popover
                ref="search"
                width="200"
                trigger="click"
            >
                <h1 style="color: #FFFFFF;background-color: #3ac1c4;margin-bottom:15px;padding:5px 0px 5px 15px; border-radius:3px;">操作人</h1>
                <div style="width:90%;height:40%;border:1px solid gray; margin:0 auto; padding:5px 5px 5px 5px;">
                    <h1>测试内容</h1>
                </div>
            </el-popover>
        </div>
    </div>
</template>
<script>
import echarts from 'echarts';
import maskStatistics from '@/axios/maskStatistics.js'

export default {
    data(){
        return{
            beginRadio:'08:30:00',
            endRadio:'08:30:00',
            search:{
                showTime:[],
                macName:'ZP-1',
                macId:'',
                machineData:[],
            },
            statistics:{
                grid:null,
            },
            grid:{
                YAxisZpData:[],
                YAxisEdData:[],
                YAxisBzData:[],
                seriesData:[],
                startTime:this.timestampToTime1(new Date(),'yy-mm-dd'),
                endTime:this.timestampToTime1(new Date(),'yy-mm-dd'),
                XstartTime:new Date(),
                XendTime:new Date(),
            },
            querySData:{
                inputMap:[],
                inputMapKey:[],
                outputMap:[],
                outputMap:[],
            },
            isfristBindEvent:true,
            ganttChartZp:null,
            ganttChartEd:null,
            ganttChartBz:null,
        }
    },
    mounted(){

    },
    created(){
        let self = this;
        self.$nextTick(()=>{
            self.init();
        });
    },
    watch:{
        $route(){
        }
    },
    computed:{
        autoHeight(){
            return this.$store.state.clientHeight-55;
        }
    },
    methods:{
        //初始化
        init(){
            let self = this;
            // self.initStatistics();
            self.getMachineData();
        },
        //初始化统计图
        initStatistics(){
            let self = this;
            self.queryStatisticsData();
        },
        //查询统计图数据
        queryStatisticsData(){
            let self = this;
            let param = {
                    macId:self.search.macId,
                    beginTime:self.timestampToTime1(self.grid.XstartTime,'yy-mm-dd hh:mm:ss'),
                    endTime:self.timestampToTime1(self.grid.XendTime,'yy-mm-dd hh:mm:ss')
            };
        //
        maskStatistics.searchGantt(param).then(res=>{
            self.querySData.inputMap = res.content.inputMap;
            self.querySData.inputMapKey = res.content.inputMapKey;
            self.querySData.outputMap = res.content.outputMap;
            self.querySData.outputMapKey = res.content.outputMapKey;
            self.grid.YAxisZpData=[];
            self.grid.YAxisZpData = self.grid.YAxisZpData.concat(self.querySData.outputMapKey);
            self.grid.YAxisZpData = self.grid.YAxisZpData.concat(self.querySData.inputMapKey);
            //加工甘特图数据
            self.setSeriesData();
            console.log(self.grid.YAxisZpData);
            self.initGanttMap();
        });
        //self.initGanttMap();
        },
        setSeriesData(){
            let self = this;
            self.grid.seriesData=[];
            //遍历输入key inputMap
            if(self.querySData.inputMap!=undefined&& self.querySData.inputMap!=null){

                self.querySData.inputMapKey.forEach(element => {
                     self.querySData.inputMap[element].forEach(inelement => {
                         let valueObj=[];
                         valueObj.push(inelement.materialName);
                         valueObj.push(inelement.startUseTime);
                         valueObj.push(inelement.endUseTime);
                         valueObj.push(inelement.materialWeight);
                         valueObj.push(inelement.materialCount);
                         valueObj.push(inelement.storageTime);
                         valueObj.push(inelement.useTimeLen);
                         valueObj.push(inelement.useUserName);
                         valueObj.push(inelement.isEnd);
                         let dataObj = {
                             name:element,
                             value:valueObj
                         };
                        self.grid.seriesData.push(dataObj);
                    });

                });
            }
            //遍历输入key outputMap
            if(self.querySData.outputMap!=undefined&& self.querySData.outputMap!=null){

                self.querySData.outputMapKey.forEach(element => {
                     self.querySData.outputMap[element].forEach(inelement => {
                         let valueObj=[];
                         valueObj.push(inelement.materialName);
                         valueObj.push(inelement.startUseTime);
                         valueObj.push(inelement.endUseTime);
                         valueObj.push(inelement.materialWeight);
                         valueObj.push(inelement.materialCount);
                         valueObj.push(inelement.storageTime);
                         valueObj.push(inelement.useTimeLen);
                         valueObj.push(inelement.useUserName);
                         valueObj.push(inelement.isEnd);
                         let dataObj = {
                             name:element,
                             value:valueObj
                         };
                        self.grid.seriesData.push(dataObj);
                    });

                });
            }
        },
        //创建统计图
        createStatistics(){
            let self = this;


        },
        //选择时间段
        showGanttMapByDate(dateVal){
            let self = this;
            if(dateVal!=undefined &&dateVal!=null){
            self.grid.XstartTime = dateVal[0];
            self.grid.XendTime = dateVal[1];
            self.initStatistics();
            }
        },
        //选择开始时间
        showGanttMapStartTime(dateVal){
            let self = this;
            if(dateVal!=undefined &&dateVal!=null){
            let beginTime_ = dateVal + " " + self.beginRadio;
            self.grid.XstartTime = beginTime_;
            self.initStatistics();
            }
        },
        //选择开始时间
        showGanttMapEndTime(dateVal){
            let self = this;
            if(dateVal!=undefined &&dateVal!=null){
            let endTime_ = dateVal + " " + self.endRadio;
            self.grid.XendTime = endTime_;
            self.initStatistics();
            }
        },
        //选择开始时间
        radioChangeStart(dateVal){
            let self = this;
            if(dateVal!=undefined &&dateVal!=null){
            let beginTime_ = self.grid.startTime + " " + dateVal;
            self.grid.XstartTime = beginTime_;
            self.initStatistics();
            }
        },
        radioChangeEnd(dateVal){
            let self = this;
            debugger;
            if(dateVal!=undefined &&dateVal!=null){
            let endTime_ = self.grid.endTime + " " + dateVal;
            self.grid.XendTime = endTime_;
            self.initStatistics();
            }
        },
        //根据所传参数时间进行该时间当天0:00与24:00的时间段点获取
        getDateAToZ(date){
            debugger;
            let self = this;
            let date1 = null;
            let date2 = null;
            if(date!=null){
            date1 =   new Date(new Date(date.toLocaleDateString()).getTime());
            date2 =  new Date(new Date(date.toLocaleDateString()).getTime()+24*60*60*1000-1);
            }else
            {
            date1 = new Date(new Date(new Date().toLocaleDateString()).getTime());
            date2 = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1);
            }

            let startTime = date1.getFullYear() + "-" + ((date1.getMonth() + 1) < 10 ? "0" + (date1.getMonth() + 1):(date1.getMonth() + 1))+ "-" + (date1.getDate() < 10 ? "0" + date1.getDate():date1.getDate()) + " " + (date1.getHours()<10?"0"+date1.getHours():date1.getHours()) + ":" + (date1.getMinutes()<10?"0"+date1.getMinutes():date1.getMinutes()) + ":" + (date1.getSeconds()<10?"0"+date1.getSeconds():date1.getSeconds());

            let endTime = date2.getFullYear() + '-' + (date2.getMonth() + 1) + '-' + date2.getDate() + ' ' + date2.getHours() + ':' + date2.getMinutes() + ':' + date2.getSeconds()
            //设置甘特图上面操作按钮栏 时间插件el-date-picker 默认展示当天时间 年-月-日《= showTime
            //设置甘特图X轴开始时间与结束时间，默认进入页面获取当天时间的0点和23点59分59秒作为开始和结束时间
            // self.grid.XstartTime = startTime;
            // self.grid.XendTime = endTime;

            // self.search.showTime.push(new Date(startTime));
            // self.search.showTime.push(new Date(endTime));
            self.grid.XstartTime = self.timestampToTime1(date,'yy-mm-dd')+' 08:30:00';
            self.grid.XendTime =self.timestampToTime1(date,'yy-mm-dd')+' 20:30:00';;
            self.initStatistics();
        },
        //查询机器信息
        getMachineData(){
            let self = this;
            let param = {
                currentPage:1,
                pageSize:1000
            };
            maskStatistics.searchMachine(param).then(res=>{
                self.search.machineData = res.content.records;
                if(self.search.machineData!=null && self.search.machineData!=undefined && self.search.machineData.length!=0){
                   self.search.macId = self.search.machineData[0].id;
                   self.search.macName =  self.search.machineData[0].name;
                }
                self.getDateAToZ(new Date());
            });
        },
        //同步机器信息
        syschMacName(val){
            let self = this;
                if(self.search.machineData!=null && self.search.machineData!=undefined && self.search.machineData.length!=0){
                    self.search.machineData.forEach(machine => {
                        if(machine.id ==val){
                            self.search.macName =  machine.name;
                            self.initStatistics();                        }
                    });
                }
        },
        //初始化甘特图
        initGanttMap(){
            let self = this;
            debugger;
            let echarts = self.$echarts;
            self.ganttChartZp = echarts.init(
                document.getElementById("zp")
            );
            self.ganttChartZp.clear(); //清除上次数据
            let option = self.setGanttChartOption();
            self.ganttChartZp.setOption(option,true);
            if(self.isfristBindEvent){
                self.listenerForClikcGanttMap();
                self.isfristBindEvent = false;
            }
        },
        //甘特图option设置
        setGanttChartOption(){
            let self =  this;
            let categories = [
                    "001",
                    "002",
                    "003",
                    "004",
                    "005",
                    "006",
                    "007",
                    "008",
                    "009",
                    "010",
                    "011",
                    "012",
                    "013",
                    "014",
                    "015",
                    "016",
                    "017",
                    "018",
                    "019",
                    "020"
                    ];
               // 绘制图表。
            let option = {
                    title: {
                        text: '生产甘特图'
                    },
                    // legend: {
                    //     y: 'top',
                    //     x:'right',
                    //     padding:[50,10,0,0],
                    //     orient:'vertical',
                    //     selected:{
                    //      首次装夹:self.trigger.isFristInstall,
                    //      次装夹:self.trigger.isInstall,
                    //      程序运行:self.trigger.isRunTime,
                    //      首检:self.trigger.isFristCheck
                    //     },
                    //     data: [
                    //      '首次装夹',
                    //      '次装夹',
                    //      '程序运行',
                    //      '首检'
                    //      ]

                    // },
                    grid: {
                       left: 150,
                       right: 115,
                       containLabel: false,
                    },
                    dataZoom: [
                        {
                            type: "slider",
                            filterMode: "weakFilter",
                            showDataShadow: true,
                            bottom: 25,
                            height: 5,
                            borderColor: "transparent",
                            backgroundColor: "#e2e2e2",
                            handleIcon:
                            "M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z",
                            handleSize: 20,
                            handleStyle: {
                            shadowBlur: 6,
                            shadowOffsetX: 1,
                            shadowOffsetY: 2,
                            shadowColor: "#aaa"
                            },
                            labelFormatter: ""
                        },
                        {
                            type: "inside",
                            filterMode: "weakFilter"
                        }
                    ],
                    xAxis: {
                        type: "time",
                        splitNumber: 40,
                        axisLabel:{
                            formatter:function(val){
                                var date= new Date(val);
                                var ym = [date.getFullYear(), date.getMonth()+1,date.getDate()-1];
                                self.showTime ="日期:"+ ym.join("-");
                                var texts=[date.getHours(),date.getMinutes()];
                                return texts.join(":");
                            }
                        },
                        splitLine: {
                                     show: true,
                                     //  改变轴线颜色
                                     lineStyle: {
                                                type:'dashed',
                                      // 使用深浅的间隔色
                                        color: ['rgba(0,0,0,0.2)']
                                            },
                                },
                        min:new Date(self.grid.XstartTime),
                        max:new Date(self.grid.XendTime),
                    },
                    yAxis: {
                        // min:0,
                        // max:29,
                        // splitNumber : 29,
                        splitLine: {
                            show: true,
                           //  改变轴线颜色
                                     lineStyle: {
                                                 type:'dashed',
                                      // 使用深浅的间隔色
                                        color: ['rgba(0,0,55,0.8)']
                                            },
                                },
                        data: self.grid.YAxisZpData,
                        axisLine: {
                            lineStyle: {
                            color: "red"
                            // color: "#000"
                            }
                        }
                    },
                    tooltip: {
                        backgroundColor: "#F6F6F6",
                        borderWidth: 1,
                        borderColor: "rgba(0,0,0,.3)",
                        triggerOn: "click",
                        confine: true,
                        enterable: true,
                        transitionDuration: 0,
                        textStyle: {
                            color: "#333"
                        },
                        extraCssText: 'box-shadow: 0 0 5px 1px rgba(255, 255, 255, 0.3);',
                        padding: [5, 10],
                        position: function (pos, params, dom, rect, size) {
                            return [pos[0] + 10, pos[1]];
                        },
                        // position: [10, 10],
                        formatter:self.tooltipHander
                    },
                    series:[
                        {
                            type: 'custom',
                            encode: {
                                x: [1,2],
                                y: 0
                                },
                            itemStyle: {
                                normal: {
                                color:self.seriesColorHander,
                                opacity: 0.9,
                                    }
                                },
                            renderItem:self.renderItem,
                            data:self.grid.seriesData,
                        },
                    ]
                };
            self.option = option;
         return option;
        },
        //渲染风格
        renderItem(params, api) {
            let categoryIndex = api.value(0);
            let start = api.coord([api.value(1), categoryIndex]);
            let end = api.coord([api.value(2), categoryIndex]);
            let height = api.size([0, 1])[1] * 1;

            let rectShape = echarts.graphic.clipRectByRect({
                x: start[0],
                y: start[1] - height / 2,
                width: end[0] - start[0],
                height: height
            }, {
                x: params.coordSys.x,
                y: params.coordSys.y,
                width: params.coordSys.width,
                height: params.coordSys.height
            });

            return rectShape && {
                type: 'rect',
                shape: rectShape,
                style: api.style()
            };
        },
        //甘特图表格处理函数
        tooltipHander(params){
            let self = this;
                    var state = params.value[8]==1?"结束":"在运行";
                    window.params = params;
                    // var res='';
                    // var operation ='&nbsp;&nbsp;<a href="javascript:void(0);"  onclick="openResponse()">实操人</a>';
                    // var detail ='&nbsp;&nbsp;<a href="javascript:void(0);"  onclick="openDeatil()">查看详情</a></br>';
                    // var operator = params.value[13]==null?"未设置":params.value[13];
                    // var realoperator = params.value[14]==null?"未设置":params.value[14];
                    // var planResultId = params.value[12];    //id
                    //     self.operator.planResultId = planResultId;
                    //     console.log("planResultId==="+self.operator.planResultId);
                    //     res = res+operation+detail;
                    // var date0 = new Date(params.value[1]);
                    // var date1 = new Date(params.value[2]);
                    // var covelVal = (date1.getTime()-date0.getTime())/1000/60;
                    // var scond = (date1.getTime()-date0.getTime())%60000;
                    //     date0 = date0.getFullYear() + "-" + (date0.getMonth() + 1)+"-"+date0.getDate()+" "+date0.getHours()+":"+date0.getMinutes()+":"+date0.getSeconds();
                    //     date1 = date1.getFullYear() + "-" + (date1.getMonth() + 1)+"-"+date1.getDate()+" "+date1.getHours()+":"+date1.getMinutes()+":"+date1.getSeconds();
                     let   res = "材料类型："+ params.value[0] + "</br>"+
                                         "重量: "+params.value[3]+"kg</br>"+
                                         "数量："+params.value[4]+"</br>"+
                                         "入库时间: "+params.value[5]+"</br>"+
                                         "开始时间："+params.value[1]+"</br>"+
                                         "结束时间："+params.value[2]+"</br>"+
                                         "持续时长："+params.value[6]+"</br>"+
                                         "操作人: "+params.value[7]+"</br>"+
                                        //  "状态："+state+"</br>"+
                                         "<hr/>";
                    return res;
        },
        //甘特图series处理函数
        seriesColorHander(params){
            let self = this;
            // try {
            //     let key = params.value[12];
            //     let operator = params.value[13];
            //     let realoperator = params.value[14];
            //         if(self.isContain(key)){
            //             return '#E062AE';
            //         }else{
            //             if((operator !=null || realoperator!=null)&&params.value[11] !=1 && params.value[11] !=2){
            //                  return '#5c7a29';
            //             }else
            //             if(params.value[11]==2){
            //                 return "#ed1941";
            //             }else if(params.value[11] ==1 ){
            //                 return "#45b97c";
            //             }
            //             return "#ffc20e";
            //         }
            // } catch (error) {

            // }
                                    return "#C6EFCE";

        },
        //点击甘特图事件监听
        listenerForClikcGanttMap(){
            let self = this;
            // if(self.ganttChart!=null){
            //     // self.ganttChart.on("dblclick",function(params){
            //     self.ganttChart.on("dblclick",function(params){
            //         self.ganttChart.clear();
            //         //self.ganttChart.off('click')
            //         console.log(params.value[12]);
            //         self.curInt =  params.value[12];
            //         if(self.isContain(params.value[12])){
            //             self.removeContain(params.value[12]);
            //         }else{
            //             self.selectSperatorArray.push(params.value[12]);
            //         }
            //         self.setGanttChartOption();
            //         self.ganttChart.setOption(self.option,false);
            //     });
            //     self.ganttChart.on("legendselectchanged", function(params) {
            //         let select = params.selected;
            //             self.trigger.isFristInstall = select.首次装夹;
            //             self.trigger.isInstall = select.次装夹;
            //             self.trigger.isRunTime = select.程序运行;
            //             self.trigger.isFristCheck = select.首检;

            //             //   self.trigger.isFristInstall,
            //             //  次装夹:self.trigger.isInstall,
            //             //  程序运行:self.trigger.isRunTime,
            //             //  首检:self.trigger.isFristCheck
            //         //self.trigger =params.selected;
            //     });
            //     window.addEventListener("resize", () => {
            //         self.ganttChart.resize();
            //     });
            // }
        },
    },
}
</script>
<style scoped>

</style>
